﻿using SF.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.admin.goods
{
    public partial class goods_list : SF.Web.UI.ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;
        protected string category_id;
        protected string keywords = string.Empty;
        //&&1 已上架 2  已下架
        protected int isOnShelf;
        protected string prolistview = string.Empty;
        protected string busnieseNum = "", appNum = "", templatesNum="";

        protected void Page_Load(object sender, EventArgs e)
        {
            this.category_id = DTRequest.GetQueryString("category_id");
            this.keywords = DTRequest.GetQueryString("keywords");
            this.isOnShelf = DTRequest.GetQueryInt("isOnShelf");

            this.pageSize = GetPageSize(10); //每页数量
            this.prolistview = Utils.GetCookie("goods_info_list_view"); //显示方式
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("goods_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
                string busnieseNum = mgr.busnieseNum.ToString();
                string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
                string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString(); 
                if (string.IsNullOrEmpty(templatesNum))
                {
                    JscriptMsg("请先在商品管理中选择模版！", "/admin/modeconfig/malltemplet_list.aspx");
                    return;
                }
                TreeBind(); //绑定类别
                RptBind(this.isOnShelf, this.category_id, " id>0 and " + Utils.getWhereByInfo(busnieseNum, appNum, templatesNum) + CombSqlTxt(this.keywords), " sort");
            }
        }

        #region 绑定类别

        /// <summary>
        /// 绑定的是类别编号 非 自增编号
        /// </summary>
        private void TreeBind()
        {
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            busnieseNum = mgr.busnieseNum.ToString();
            appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            BLL.sf_goods_types bll = new BLL.sf_goods_types();
            DataTable dt = bll.GetList(0, Utils.getWhereByInfo(busnieseNum, appNum, templatesNum), "id asc").Tables[0];
            this.ddlCategoryId.Items.Clear();
            this.ddlCategoryId.Items.Add(new ListItem("所有分类", ""));
            foreach (DataRow dr in dt.Rows)
            {
                string Id = dr["typeNum"].ToString();
                int ClassLayer = int.Parse(dr["class_layer"].ToString());
                string Title = dr["name"].ToString().Trim();
                if (ClassLayer == 1)
                {
                    this.ddlCategoryId.Items.Add(new ListItem(Title, Id));
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    this.ddlCategoryId.Items.Add(new ListItem(Title, Id));
                }
            }
        }
        #endregion

        #region 数据绑定
        private void RptBind(int _isOnShelf, string _category_id, string _strWhere, string _orderby)
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            if (!String.IsNullOrEmpty(_category_id))
            {
                this.ddlCategoryId.SelectedValue = _category_id.ToString();
            }
            if (_isOnShelf > 0)
            {
                ddlShelf.SelectedValue = _isOnShelf.ToString();
            }
            this.txtKeywords.Text = this.keywords;
            //图表或列表显示
            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            switch (this.prolistview)
            {
                case "Txt":
                    this.rptList2.Visible = false;
                    this.rptList1.DataSource = bll.GetList(_isOnShelf, _category_id, this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    this.rptList1.DataBind();
                    break;
                default:
                    this.rptList1.Visible = false;
                    this.rptList2.DataSource = bll.GetList(_isOnShelf, _category_id, this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    this.rptList2.DataBind();
                    break;
            }
            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}&page={3}",
                _isOnShelf.ToString(),
                 _category_id.ToString(), this.keywords, "__id__");
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (names like '%"
                    + _keywords + "%' or brandName like '%" + _keywords + "%' or place like '%" + _keywords + "%') ");
            }
            return strTemp.ToString();
        }
        #endregion

        #region 返回图文每页数量
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("goods_info_page_size"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //设置操作
        protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            ChkAdminLevel("goods_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            this.RptBind(this.isOnShelf, this.category_id, "  id>0" + CombSqlTxt(this.keywords), "sort asc,id desc");
        }

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}",
                this.isOnShelf.ToString(), this.category_id.ToString(), txtKeywords.Text));
        }

        //筛选类别
        protected void ddlCategoryId_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}",
                 ddlShelf.SelectedValue, ddlCategoryId.SelectedValue, this.keywords));
        }
        //&&上架与下架处理条件筛选
        protected void ddlShelf_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}",
                 ddlShelf.SelectedValue, ddlCategoryId.SelectedValue, this.keywords));
        }

        //设置文字列表显示
        protected void lbtnViewTxt_Click(object sender, EventArgs e)
        {
            Utils.WriteCookie("goods_info_list_view", "Txt", 14400);
            Response.Redirect(Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}&page={3}",
                this.isOnShelf.ToString(), this.category_id.ToString(), this.keywords, this.page.ToString()));
        }

        //设置图文列表显示
        protected void lbtnViewImg_Click(object sender, EventArgs e)
        {
            Utils.WriteCookie("goods_info_list_view", "Img", 14400);
            Response.Redirect(Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}&page={3}",
                 this.isOnShelf.ToString(), this.category_id.ToString(), this.keywords, this.page.ToString()));
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("goods_info_page_size", _pagesize.ToString(), 43200);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}",
                 this.isOnShelf.ToString(), this.category_id.ToString(), this.keywords));
        }

        //保存排序 done
        protected void btnSave_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("goods_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            Repeater rptList = new Repeater();
            switch (this.prolistview)
            {
                case "Txt":
                    rptList = this.rptList1;
                    break;
                default:
                    rptList = this.rptList2;
                    break;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                long id = Convert.ToInt64(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                int sortId;
                if (!int.TryParse(((TextBox)rptList.Items[i].FindControl("txtSortId")).Text.Trim(), out sortId))
                {
                    sortId = 99;
                }
                bll.UpdateField(id, "sort=" + sortId.ToString());
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "保存商品排序"); //记录日志
            JscriptMsg("保存排序成功啦！", Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}",
                 this.isOnShelf.ToString(), this.category_id.ToString(), this.keywords));
        }

        //&&上架
        protected void btnOnShelf_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("goods_list", DTEnums.ActionEnum.OnShelf.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            Repeater rptList = new Repeater();
            switch (this.prolistview)
            {
                case "Txt":
                    rptList = this.rptList1;
                    break;
                default:
                    rptList = this.rptList2;
                    break;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                long id = Convert.ToInt64(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (bll.UpdateField(id, " status=1 "))
                    {
                        sucCount++;
                    }
                    else
                    {
                        errorCount++;
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "上架商品内容成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("上架成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}", this.isOnShelf.ToString(), this.category_id.ToString(), this.keywords));
        }
        //批量删除 done
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("goods_list", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            Model.sf_goods_info model;
            BLL.sf_goods_img bllImg = new BLL.sf_goods_img();
            BLL.sf_goods_orderdetal detaBll = new BLL.sf_goods_orderdetal();
            Repeater rptList = new Repeater();
            switch (this.prolistview)
            {
                case "Txt":
                    rptList = this.rptList1;
                    break;
                default:
                    rptList = this.rptList2;
                    break;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (detaBll.GetList("goodsNum='" + bll.GetModel(id).goodsNum + "'").Tables[0].Rows.Count <= 0)
                    {
                        if (bll.Delete(id))
                        {
                            sucCount++;
                            //&&删除对应的图片
                            //&&封面图片、其它图片
                            model = bll.GetModel(id);
                            if (model != null)
                            {
                                bllImg.DeleteFile(model.goodsImgs);
                                bllImg.DeleteFile(model.showImgs);
                            }
                        }
                        else
                        {
                            errorCount++;
                        }
                    }
                    else
                    {
                        errorCount++;
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除商品内容成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！ 含有订单数据，不能删除，可进行下架操作！", Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}", this.isOnShelf.ToString(), this.category_id.ToString(), this.keywords));
        }


        //&&批量下架 done
        protected void btnOffShelf_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("goods_list", DTEnums.ActionEnum.OffShelf.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            BLL.sf_goods_orderdetal detaBll = new BLL.sf_goods_orderdetal();
            Repeater rptList = new Repeater();
            switch (this.prolistview)
            {
                case "Txt":
                    rptList = this.rptList1;
                    break;
                default:
                    rptList = this.rptList2;
                    break;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (bll.UpdateField(id, " status=2 "))
                    {
                        sucCount++;
                    }
                    else
                    {
                        errorCount++;
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "下架商品内容成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("下架成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("goods_list.aspx", "isOnShelf={0}&category_id={1}&keywords={2}", this.isOnShelf.ToString(), this.category_id.ToString(), this.keywords));
        }
    }
}